package org.lc.stk.service.question.impl;

import java.util.List;

import org.lc.stk.dao.question.DifficultySchemaRepository;
import org.lc.stk.model.question.attrs.DifficultySchema;
import org.lc.stk.service.exception.BusinessException;
import org.lc.stk.service.question.DifficultySchemaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DifficultySchemaServiceImpl implements DifficultySchemaService {

    @Autowired
    private DifficultySchemaRepository difficultySchemaRepository;

    @Override
    @Transactional
    public DifficultySchema create(DifficultySchema schema) {
        // 验证名称是否重复
        if (existsByName(schema.getName(), null)) {
            throw new BusinessException("难度方案名称已存在");
        }

        // TODO: 验证难度等级数量是否与类型匹配
        return difficultySchemaRepository.save(schema);
    }

    @Override
    @Transactional
    public DifficultySchema update(DifficultySchema schema) {
        if (!difficultySchemaRepository.existsById(schema.getId())) {
            throw new BusinessException("难度方案不存在");
        }

        // 验证名称是否重复
        if (existsByName(schema.getName(), schema.getId())) {
            throw new BusinessException("难度方案名称已存在");
        }

        // TODO: 验证难度等级数量是否与类型匹配
        return difficultySchemaRepository.save(schema);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        if (!difficultySchemaRepository.existsById(id)) {
            throw new BusinessException("难度方案不存在");
        }

        // TODO: 检查难度方案是否被使用
        difficultySchemaRepository.deleteById(id);
    }

    @Override
    public DifficultySchema findById(Long id) {
        return difficultySchemaRepository.findById(id)
            .orElseThrow(() -> new BusinessException("难度方案不存在"));
    }

    @Override
    public List<DifficultySchema> findAll() {
        return difficultySchemaRepository.findAll();
    }

    @Override
    public boolean existsByName(String name, Long excludeId) {
        return difficultySchemaRepository.existsByNameAndIdNot(name, excludeId);
    }

    @Override
    public List<DifficultySchema> findByType(DifficultySchema.Type type) {
        return difficultySchemaRepository.findByType(type);
    }

    @Override
    public DifficultySchema getDefaultSchema() {
        return difficultySchemaRepository.findDefaultSchema();
    }

    @Override
    public boolean existsById(Long id) {
        return difficultySchemaRepository.existsById(id);
    }
}